#!/bin/bash
#01 00 * * * ${PATH}CutLog.sh
#author merci

#格式化日期格式
D=$(date +%Y%m%d)
#nginx日志目录路径
NGINXLOG="/usr/local/nginx/logs/"
#nginx切割保存日志目录
SAVEPATH="/data/logs/nginx/"
#nginx切割保存日志目录（日期建立）
LOGPATH=${SAVEPATH}$D
#日志名
LOGNAME="access.log"
#nginx错误日志目录
ERRPATH=${SAVEPATH}$D
#错误日志名
ERRNAME="error.log"
#日志保存最近几天
SAVEDAY=7

function cut_log(){
	mkdir -p ${LOGPATH}
	if [ -f "${NGINXLOG}${LOGNAME}" ];then
		mv ${NGINXLOG}${LOGNAME} ${LOGPATH}/${LOGNAME}
	fi
	if [ -f "${NGINXLOG}${ERRNAME}" ];then
		mv ${NGINXLOG}${ERRNAME} ${LOGPATH}/${ERRNAME}
	fi
}
function del_backup(){
	declare -a backup
	backuplist=`ls ${SAVEPATH}`
	i=0
	for a in ${backuplist}
	do
		backup[$i]=$a
		let i=$i+1
	done
	if [ "${#backup[@]}" -gt "${SAVEDAY}" ];then
	#最旧的备份
	# ${backup[0]}
	#----------------------------
        #最新的备份
        # n=`expr ${#backup[@]} - 1`;${backup[$n]} 或者 ${backup[@]: -1}
        #----------------------------
		rm -rf ${SAVEPATH}${backup[0]} >/dev/null 2>&1
	else
		exit 0
	fi
}

cut_log
del_backup